import {usePmAppStore} from "@/stores";
import {usePmLoginApi} from "@/api/pm/login";
import { http } from '@/utils/http'
import {CustomRequestOptions} from "@/interceptors/request";
import {gotoH5PasskeyLogin} from "@/interceptors/route";

let isRefreshToken: boolean = false;
let requestList: any[] = [];

export async function usePmRequestIcp(options: CustomRequestOptions) {
  if (!isRefreshToken) {
    isRefreshToken = true;
    // 1. 如果获取不到刷新令牌，则只能执行登出操作
    if (!usePmAppStore().getRefreshToken()) {
      gotoH5PasskeyLogin()
      return;
    }
    // 2. 进行刷新访问令牌
    try {
      const refreshTokenRes = await usePmLoginApi().refreshToken()
      if (refreshTokenRes.code !== 0) {
        gotoH5PasskeyLogin()
        return;
      }
      // 2.1 刷新成功，则回放队列的请求 + 当前请求
      usePmAppStore().setToken(refreshTokenRes.data.accessToken)
      window.location.reload();
      return;
    } catch (e) {// 为什么需要 catch 异常呢？刷新失败时，请求因为 Promise.reject 触发异常。
      // 2.2 刷新失败，只回放队列的请求
      requestList.forEach(cb => cb())
      gotoH5PasskeyLogin()
    } finally {
      requestList = []
      isRefreshToken = false
    }
  } else {
    // 添加到队列，等待刷新获取到新的令牌
    return new Promise(resolve => {
      requestList.push(() => {
        resolve(http(options))
      })
    })
  }
}
